<?php

namespace app\api\controller\v49;

use app\aliyun\controller\AliyunFilterWordV2;
use app\api\controller\v2\Auth;
use app\common\cachemodel\ai_chat_room\AiChatFirstTxt;
use app\common\cachemodel\ai_chat_room\AiChatLastSendTimeRecord;
use app\common\cachemodel\ai_chat_room\AiChatRecord;
use app\common\cachemodel\ai_chat_room\AiChatRecordDetails;
use app\common\cachemodel\ai_chat_room\AiChatStoryLine;
use app\common\cachemodel\ai_chat_room\AiChatTag;
use app\common\cachemodel\ai_chat_room\AiChatUserConfig;
use app\common\cachemodel\ai_chat_room\AiChatUserDuration;
use app\common\cachemodel\ai_chat_room\AiChatUserDurationChangeRecord;
use app\common\cachemodel\Recode;
use app\common\lib\Util;
use app\common\model\Informant;
use app\common\model\MiddleInformant;
use app\common\service\AiChatRoomParse;
use app\common\service\AiChatRoomService;
use think\Cache;
use think\Log;
use think\response\Json;

class AiChatRoomUser extends Auth
{
    /**
     * @return Json
     */
    public function createSkip()
    {
        $cacheKey = 'ai_chat_room:create_skip:user:' . $this->user['id'];
        // 记录点击跳过缓存 30天
        Cache::set($cacheKey, 1, 86400 * 30);

        return show(config('code.success'), '请求成功');
    }

    /**
     * 获取创建聊天室页面的介绍信息
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getRoomCreateIntro()
    {
        $type = input('type/d', 0);
        $healChatId = input('heal_chat_id/d', 0);
        $configData = config('ai_chat_room');
        if (!isset($configData['type_list'][$type]))
        {
            return show(config('code.error'), '请选择正确的聊天室类型');
        }
        $typeConfig = $configData['type_list'][$type];
        $optionData = (new AiChatTag())->getChatTagData($type);
        if ($healChatId)
        {   // 编辑情况
            $aiChatRecordModel = new AiChatRecord();
            $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
            $configDataDefault = (new AiChatUserConfig())->getInfoById($aiChatRecordData['config_id']);
            $defaultConfig = $configDataDefault['config']['config'];
            foreach ($optionData as $key => $item)
            {
                unset($optionData[$key]['id'], $optionData[$key]['option_ids']);
                foreach ($item['option_list'] as $k => $v)
                {
                    if ($optionData[$key]['option_list'][$k]['node'])
                    {
                        unset($optionData[$key]['option_list'][$k]['node']['id'], $optionData[$key]['option_list'][$k]['node']['option_ids']);
                    }
                    if (in_array($v['id'], $defaultConfig[$item['key']]['ids']))
                    {
                        $optionData[$key]['option_list'][$k]['is_selected'] = 1;
                        if ($optionData[$key]['option_list'][$k]['node'])
                        {
                            foreach ($v['node']['option_list'] as $k1 => $v1)
                            {
                                if (in_array($v1['id'], $defaultConfig[$v['node']['key']]['ids']))
                                {
                                    $optionData[$key]['option_list'][$k]['node']['option_list'][$k1]['is_selected'] = 1;
                                }
                            }
                        }
                    }
                }
            }
            $defaultAvatar = $aiChatRecordData['avatar'];
            $defaultName = $aiChatRecordData['name'];
            $defaultDesc = $configDataDefault['config']['desc'];
        } else
        {   // 新建情况
            $defaultSex = 2;    // 默认选择 女   1=>男 2=>女
            if ($this->user['rid'])
            {
                $recordInfo = (new Recode())->getInfoById($this->user['rid'], ['id', 'type']);
                $type = (int)($recordInfo['type'] ?? 1);
                $defaultSex = $type === 2 ? 1 : 2;
            }
            foreach ($optionData as $key => $item)
            {
                unset($optionData[$key]['id'], $optionData[$key]['option_ids']);
                foreach ($item['option_list'] as $k => $v)
                {
                    if ($optionData[$key]['option_list'][$k]['node'])
                    {
                        unset($optionData[$key]['option_list'][$k]['node']['id'], $optionData[$key]['option_list'][$k]['node']['option_ids']);
                    }
                }
                if ($item['key'] === 'sex')
                {
                    foreach ($item['option_list'] as $k => $v)
                    {
                        if (($defaultSex === 1 && strpos($v['name'], '男') !== false) || ($defaultSex === 2 && strpos($v['name'], '女') !== false))
                        {
                            $optionData[$key]['option_list'][$k]['is_selected'] = 1;
                        }
                        if ($optionData[$key]['option_list'][$k]['node'])
                        {
                            unset($optionData[$key]['option_list'][$k]['node']['id'], $optionData[$key]['option_list'][$k]['node']['option_ids']);
                        }
                    }
                }
            }
        }

        $resData = [
            'option_data' => $optionData,
            'page_title' => $typeConfig['name'],
            'progress_desc' => '现在我需要初步了解你的诉求',
            'name_max_length' => $configData['name_max_length'],    // 名字最大长度
            'desc_max_length' => $typeConfig['desc_max_length'],    // 陪聊对象的要求最大长度
            'desc_placeholder' => $typeConfig['desc_placeholder'],   // 陪聊对象的要求内容默认提示语
            'default_avatar' => $defaultAvatar ?? '', // 【编辑的情况】默认头像
            'default_name' => $defaultName ?? '',   // 【编辑的情况】默认名字
            'default_desc' => $defaultDesc ?? '',   // 【编辑的情况】默认陪聊对象的要求
        ];
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     *  随机获取一个头像
     * @return \think\response\Json
     */
    public function randomAvatar()
    {
        $config = input('config/s', '');
        $type = input('type/d', 0);
        $oldAvatar = input('old_avatar/s', '');
        $configData = config('ai_chat_room');
        if (!isset($configData['type_list'][$type]))
        {
            return show(config('code.error'), '请选择正确的聊天室类型');
        }
        if (empty($config))
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $configArr = json_decode($config, true);
        if (!$configArr || !isset($configArr['sex_type']))
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $avatar = '';
        foreach ($configData['default_avatar'] as $item)
        {
            if (in_array((int)$configArr['sex_type'], $item['ids'], true))
            {
                $avatarList = array_diff($item['avatar_list'], [$oldAvatar]);
                $avatarList = array_values($avatarList);
                $random_key = array_rand($avatarList);
                $avatar = $avatarList[$random_key];
                break;
            }
        }
        if (empty($avatar))
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }

        $resData = [
            'avatar' => $avatar,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 匹配聊天室星盘信息
     * @return \think\response\Json
     */
    public function matchAstr()
    {
        $config = input('config/s', '');
        $type = input('type/d', 0);
        $configData = config('ai_chat_room');
        if (!isset($configData['type_list'][$type]))
        {
            return show(config('code.error'), '请选择正确的聊天室类型');
        }
        if (empty($config))
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $configArr = json_decode($config, true);
        if (!$configArr || !isset($configArr['sex_type']))
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $sexType = (int)$configArr['sex_type'];
        $tagList = [];
        foreach ($configData['astr_tag']['tag1'] as $datum)
        {
            if (in_array($sexType, $datum['ids'], true))
            {
                $tagList = $datum['tags'];
                break;
            }
        }
        $optionKey = $configData['astr_tag']['tag2']['keys'][$type] ?? '';
        if ($optionKey)
        {
            if (!isset($configArr[$optionKey]) || empty($configArr[$optionKey]))
            {
                return show(config('code.error'), '请求异常，请稍后再试～');
            }
            $option2 = $configArr[$optionKey];
            $option2Arr = explode(',', $option2);
            $option2Id = (int)current($option2Arr);

            foreach ($configData['astr_tag']['tag2']['tag_list'] as $datum)
            {
                if (in_array($option2Id, $datum['ids'], true))
                {
                    $random_key = array_rand($datum['tags']);
                    $tagList[] = $datum['tags'][$random_key];
                    break;
                }
            }
        }
        $resData = [
            'title' => '根据你的选择已为你匹配TA的星盘配置是：',
            'tags' => $tagList,
        ];
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 创建或编辑 聊天室基础设定
     * @return \think\response\Json
     */
    public function createOrEditRoom()
    {
        $config = input('config/s', '');
        $type = input('type/d', 0);
        $avatar = input('avatar/s', '');
        $name = input('name/s', '');
        $desc = input('desc/s', '');
        $healChatId = input('heal_chat_id/d', 0);
        $configData = config('ai_chat_room');
        if (!isset($configData['type_list'][$type]))
        {
            return show(config('code.error'), '请选择正确的聊天室类型');
        }
        $data = [
            'config' => json_decode($config, true),
            'type' => $type,
            'avatar' => $avatar,
            'name' => $name,
            'desc' => $desc,
        ];
        if (Util::commentCheck($this->user['id'], [
            'action' => 'AiChatRoomUser.createOrEditRoom',
            'config' => $config,
            'type' => $type,
            'avatar' => $avatar,
            'name' => $name,
            'desc' => $desc,
            'heal_chat_id' => $healChatId,
        ], 3))
        {// mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $res = AiChatRoomService::paramCheck($data, $configData);
        if (!$res['status'])
        {
            return show(config('code.error'), $res['msg']);
        }
        $aiChatRecordModel = new AiChatRecord();
        $aiChatUserConfigModel = new AiChatUserConfig();
        if ($healChatId)
        {   // 编辑情况
            $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
            if (!$aiChatRecordData || $aiChatRecordData['uid'] != $this->user['id'])
            {
                return show(config('code.error'), '服务异常，伙伴不存在～');
            }
            $aiChatUserConfigModel->UpdateData($aiChatRecordData['config_id'], ['config' => ['config' => $res['data'], 'desc' => $desc]]);
            // 更新 头像和昵称
            $aiChatRecordModel->UpdateData2($healChatId, ['avatar' => $avatar, 'name' => $name,]);
        } else
        {   // 新增 伙伴
            $slId = 0;  // 默认剧情ID = 0 无剧情
            if ($configData['type_list'][$type]['is_story_line'] === 1)
            {   // 随机一个 剧情
                $slId = $aiChatUserConfigModel->randStoryLineIds($res['data']);
            }
            $insertConfig = [
                'uid' => $this->user['id'],
                'type' => $type,
                'config' => json_encode(['config' => $res['data'], 'desc' => $desc], JSON_UNESCAPED_UNICODE),
                'sl_id' => $slId,
                'create_time' => $this->request->time(),
                'update_time' => $this->request->time(),
            ];
            $configId = $aiChatUserConfigModel->SaveData($insertConfig);
            $insertData = null;
            if ($slId)
            {   //  写入 剧情信息
                $aiChatStoryLineModel = new AiChatStoryLine();
                $storyLineData = $aiChatStoryLineModel->getInfoById($slId);
                $insertData = [
                    'chat_id' => 0,
                    'uid' => $this->user['id'],
                    'type' => 1,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => $storyLineData['first_msg'], // 提问问题
                    'data_type' => 1,
                    'extend' => ['is_first' => 1, 'sl_id' => $slId],  // stream = 1 获取流式数据 2 结果已获取
                    'result_data' => '',
                    'option_id' => '',
                    'pid' => 0,
                    'create_time' => $this->request->time(),
                ];
            }
            $initChatData = [
                'uid' => $this->user['id'],
                'config_id' => $configId,
                'avatar' => $avatar,
                'name' => $name,
                'type' => $type,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $this->request->time(),
                'update_time' => $this->request->time(),
            ];
            $healChatId = $aiChatRecordModel->SaveData($initChatData);
            if ($insertData)
            {
                $insertData['chat_id'] = $healChatId;
                $aiChatRecordDetailsModel = new AiChatRecordDetails();
                $resData = $aiChatRecordDetailsModel->SaveData($healChatId, [$insertData]);
                $chatDetailId = $resData[0]['id'];

                $aiChatRecordModel->UpdateData2($healChatId, ['last_chat_detail_id' => $chatDetailId, 'last_chat_detail_time' => $this->request->time(),]);
            }
        }
        // 完成 个性配置 时长任务
        (new AiChatUserDurationChangeRecord())->durationTaskSuccess($this->user['id'], 1);

        return show(config('code.success'), '请求成功', ['heal_chat_id' => $healChatId]);
    }

    /**
     * 聊天室我的伙伴列表
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getRoomList()
    {
        $aiChatRecordModel = new AiChatRecord();
        $pageData = $aiChatRecordModel->getListPage($this->user['id'], 'update_time', [], 0, 'desc', 0);

        $pageData['data'] = $aiChatRecordModel->dataInit($pageData['data']);

        $pageData['data'] = $aiChatRecordModel->pageDataResert($pageData['data']);

        if ($pageData['current_page'] === $pageData['last_page'])
        {
            $defaultData = $aiChatRecordModel->getDefaultUserData($this->user);
            if ($defaultData)
            {
                $pageData['data'] = array_merge($pageData['data'], $defaultData);
            }
        }

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 删除 聊天对话记录
     * @return \think\response\Json
     * @throws \Exception
     */
    public function delRoomId()
    {
        $healChatId = input('heal_chat_id/d', 0);
        if (!$healChatId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $configData = config('ai_chat_room');
        if (in_array($healChatId, $configData['default_room_ids'], true))
        {   // 默认聊天室
            $sex = $healChatId % 10;
            $i = $healChatId - $sex;
            $aiChatLastSendTimeRecordModel = new AiChatLastSendTimeRecord();
            $lastData = $aiChatLastSendTimeRecordModel->getDataInfo($this->user['id']);
            $useIdType = $lastData['extend']['use_type'] ?? [];
            if (isset($useIdType[$i]))
            {
                return show(config('code.success'), '删除成功');
            }
            $useIdType[$i] = 0;
            $lastData['extend']['use_type'] = $useIdType;
            $aiChatLastSendTimeRecordModel->UpdateData($lastData['id'], $this->user['id'], ['extend' => json_encode($lastData['extend'], JSON_UNESCAPED_UNICODE)]);

            return show(config('code.success'), '删除成功');
        }
        $aiChatRecordModel = new AiChatRecord();
        $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
        if (!$aiChatRecordData || $aiChatRecordData['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '伙伴不存在或已删除');
        }

        $res = $aiChatRecordModel->delRoom($this->user['id'], $healChatId);
        if ($res)
        {
            return show(config('code.success'), '删除成功');
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 聊天室对话记录详情
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getRoomChatDetails()
    {
        $healChatId = input('heal_chat_id/d', 0);
        $minId = input('min_id/d', 0);
        $configData = config('ai_chat_room');
        $aiChatRecordModel = new AiChatRecord();
        $aiChatRecordDetailsModel = new AiChatRecordDetails();
        $slId = 0;
        if (in_array($healChatId, $configData['default_room_ids'], true))
        {   // 默认聊天室
            $sex = $healChatId % 10;
            $i = $healChatId - $sex;
            $aiChatLastSendTimeRecordModel = new AiChatLastSendTimeRecord();
            $lastData = $aiChatLastSendTimeRecordModel->getDataInfo($this->user['id']);
            $useIdType = $lastData['extend']['use_type'] ?? [];
            do
            {
                if (isset($useIdType[$i]))
                {
                    $aiChatRecordData = $aiChatRecordModel->getInfoById($useIdType[$i]);
                    if ($aiChatRecordData)
                    {   // 历史
                        $healChatId = $useIdType[$i];
                        $pageData = $aiChatRecordDetailsModel->getPageDatas($healChatId, 10, $minId);
                        break;
                    }
                }
                $defaultRoomConfig = $configData['default_user'][$i][$sex];
                if ($defaultRoomConfig['sl_id'])
                {
                    $randIndex = array_rand($defaultRoomConfig['sl_id']);
                    $defaultRoomConfig['sl_id'] = $defaultRoomConfig['sl_id'][$randIndex];
                    $slId = $defaultRoomConfig['sl_id'];
                }
                $aiChatRecordData = $aiChatRecordModel->addDefaultRoom($this->user['id'], $defaultRoomConfig);
                $healChatId = $aiChatRecordData['id'];
                $pageData = ['total' => 0, 'surplus_num' => 0, 'data' => [],];
                $useIdType[$i] = $healChatId;
                $lastData['extend']['use_type'] = $useIdType;
                $aiChatLastSendTimeRecordModel->UpdateData($lastData['id'], $this->user['id'], ['extend' => json_encode($lastData['extend'], JSON_UNESCAPED_UNICODE)]);
            } while (false);
        } else
        {
            $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
            $pageData = $aiChatRecordDetailsModel->getPageDatas($healChatId, 10, $minId);
        }
        $roomConfigData = (new AiChatUserConfig())->getInfoById($aiChatRecordData['config_id']);
        if ($roomConfigData['sl_id'] && !$slId)
        {
            $slId = $roomConfigData['sl_id'];
        }
        if (empty($pageData['data']) && $minId === 0)
        {   // 初始化 对话消息
            if ($slId)
            {
                $aiChatStoryLineModel = new AiChatStoryLine();
                $storyLineData = $aiChatStoryLineModel->getInfoById($slId);
                $firstTxt = $storyLineData['first_msg'];
            } else
            {
                $firstTxt = (new AiChatFirstTxt())->randFirstTxt($roomConfigData['config']['config']);
            }
            if ($firstTxt)
            {
                $insertData = [
                    [
                        'chat_id' => $healChatId,
                        'uid' => $this->user['id'],
                        'type' => 1,    //  1=>APP消息 2=>用户发送消息
                        'title' => '',
                        'content' => $firstTxt, // 提问问题
                        'data_type' => 1,
                        'extend' => ['is_first' => 1, 'sl_id' => $slId],  // stream = 1 获取流式数据 2 结果已获取
                        'result_data' => '',
                        'option_id' => '',
                        'pid' => 0,
                        'create_time' => $this->request->time(),
                    ],
                ];
                $res = $aiChatRecordDetailsModel->SaveData($healChatId, $insertData);
                $pageData['data'] = $res;

                $aiChatRecordModel->UpdateData($healChatId, $this->user['id'], [
                    'last_chat_detail_id' => $res[0]['id'],
                    'last_chat_detail_time' => $this->request->time(),
                ]);
            }
        }

        $pageData['data'] = $aiChatRecordDetailsModel->dataListResert($pageData['data']);
        $roomTypeConfig = $configData['type_list'][$roomConfigData['type']];
        $chatDuration = (new AiChatUserDuration())->getUserDuration($this->user['id'], true);
        if ($aiChatRecordData['new_msg'] > 0)
        {   // 未读数 已读
            $aiChatRecordModel->UpdateData($healChatId, $this->user['id'], ['new_msg' => 0]);
        }
        $resData = [
            'total' => $pageData['total'],
            'surplus_num' => $pageData['surplus_num'],
            'avatar' => $aiChatRecordData['avatar'],
            'name' => $aiChatRecordData['name'],
            'tag' => $roomTypeConfig['tag_icon'],
            'type' => $roomConfigData['type'],
            'is_story_line' => $roomConfigData['sl_id'] ? 1 : 0,
            'story_line' => $roomConfigData['story_line_content'] ?? '',
            'duration' => $chatDuration['res_duration'],
            'data' => $pageData['data'],
            'heal_chat_id' => $healChatId,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    public function getRoomConfig()
    {
        $healChatId = input('heal_chat_id/d', 0);
        if (!$healChatId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $aiChatRecordModel = new AiChatRecord();
        $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
        if (!$aiChatRecordData || $aiChatRecordData['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $roomConfigData = (new AiChatUserConfig())->getInfoById($aiChatRecordData['config_id']);

        $tagDatas = (new AiChatTag())->getConfigTagsData($roomConfigData['config']['config']);

        $resData = [
            'tip' => ['基础设定', '(直接关系到陪聊体验，请及时修改或新建聊天)'],
            'tags' => $tagDatas,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    public function sendMsg()
    {
        $healChatId = input('heal_chat_id/d', 0);
        $content = input('content/s', '');
        if (empty($content))
        {
            return show(config('code.error'), '请输入聊天的内容');
        }
        if (mb_strlen($content) > 30)
        {
            return show(config('code.error'), '聊天的内容最多30字');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'AiChatRoomUser.sendQuestion', 'content' => $content, 'heal_chat_id' => $healChatId], 3) && (int)$this->user['id'] != 10834769)
        {// mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $aliRes = AliyunFilterWordV2::checkAIText($content);
        if ($aliRes['status'] === false)
        {
            return show(0, '检测到敏感内容');
        }
        $nowTimw = $this->request->time();
        $aiChatRecordModel = new AiChatRecord();
        $aiChatRecordDetailsModel = new AiChatRecordDetails();
        $aiChatUserDurationModel = new AiChatUserDuration();
        $userChatDuration = $aiChatUserDurationModel->getUserDuration($this->user['id']);
        if ($userChatDuration['res_duration'] <= 0)
        {
            if ($userChatDuration['status'] === 1)
            {
                $aiChatUserDurationModel->userDurationEnd($this->user['id']);
            }
            return show(config('code.error'), '陪聊时长已用完～');
        }
        $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
        if (!$aiChatRecordData || $aiChatRecordData['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '服务异常，伙伴不存在～');
        }
        $insertData = [
            [   // 用户提问消息
                'chat_id' => $healChatId,
                'uid' => $this->user['id'],
                'type' => 2,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => $content, // 提问问题
                'data_type' => 1,
                'extend' => [],  //
                'result_data' => '',
                'option_id' => '',
                'pid' => 0,
                'create_time' => $nowTimw,
            ], [
                'chat_id' => $healChatId,
                'uid' => $this->user['id'],
                'type' => 1,    //  1=>APP消息 2=>用户发送消息
                'title' => '',
                'content' => '', // 提问问题
                'data_type' => 1,
                'extend' => ['stream' => 1],  // stream = 1 获取流式数据 2 结果已获取
                'result_data' => '',
                'option_id' => '',
                'pid' => 0,
                'create_time' => $nowTimw,
            ],
        ];
        $resData = $aiChatRecordDetailsModel->SaveData($healChatId, $insertData);
        if ($resData)
        {   // 更新 记录用户最后发送消息时间
            (new AiChatLastSendTimeRecord())->UpdateData(0, $this->user['id'], [
                'chat_id' => $healChatId,
                'last_send_time' => $nowTimw,
            ]);
            $chatDetailId = $resData[0]['id'];
            $aiChatRecordModel->UpdateData($healChatId, $this->user['id'], [
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $nowTimw,
            ]);
            // 陪聊 进行中
            $aiChatUserDurationModel->userDurationStart($this->user['id']);

            unset($resData[0]); // 只返回答案信息
            $resData = $aiChatRecordDetailsModel->dataListResert($resData);
            if (isset($resData[0]))
            {
                $resData = $resData[0];
                if ($resData['is_stream_reload'] === 1)
                {
                    $resData['content'] = '';
                }
                unset($resData['is_stream_reload']);
                $resData['stream'] = 1;
                $resData['duration'] = $userChatDuration['res_duration'];
                return show(config('code.success'), '请求成功', $resData);
            }
        }
        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    public function getMsgStream()
    {
        $healChatId = input('heal_chat_id/d', 0);
        $chatDetailId = input('id/d', 0);
        if (!$healChatId || !$chatDetailId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'getMsgStream', 'heal_chat_id' => $healChatId, 'id' => $chatDetailId], 3) && (int)$this->user['id'] != 12346744)
        {
            return '';
        }
        $aiChatRecordModel = new AiChatRecord();
        $aiChatRecordDetailsModel = new AiChatRecordDetails();
        $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
        if (!$aiChatRecordData || $aiChatRecordData['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '服务异常，伙伴不存在～');
        }
        $chatDetailInfo = $aiChatRecordDetailsModel->getInfoById($chatDetailId);
        if (!$chatDetailInfo || $chatDetailInfo['type'] !== 1 || $chatDetailInfo['uid'] !== $this->user['id'])
        {
            return show(config('code.error'), '服务异常，消息不存在～');
        }
        if ($chatDetailInfo['extend']['stream'] === 2)
        {
            echo $chatDetailInfo['content'];
            return;
        }
        $parentChatDetailInfo = $aiChatRecordDetailsModel->getInfoById($chatDetailInfo['pid'], ['content']);
        if (empty($parentChatDetailInfo['content']))
        {
            return;
        }
        // 获取配置信息
        $roomConfigData = (new AiChatUserConfig())->getInfoById($aiChatRecordData['config_id']);
        $queryStr = AiChatRoomParse::getMsgParseStreamData([
            'msg' => $parentChatDetailInfo['content'],
            'chat_id' => $healChatId,
            'parent_chat_detail_id' => $chatDetailInfo['pid'],
            'chat_detail_id' => $chatDetailId,
            'name' => $aiChatRecordData['name'],
        ], $roomConfigData);

        $chatDetailInfo['extend']['stream'] = 2;
        if (strpos($queryStr, 'θ') !== false)
        {
            $queryStr = '准准认为你的问题包含敏感信息，换个问题再试试吧。';
            $chatDetailInfo['extend']['answer_violation'] = 1;  // 答案违规
        }
        $aiChatRecordDetailsModel->UpdateData($chatDetailId, ['content' => $queryStr, 'extend' => json_encode($chatDetailInfo['extend'], JSON_UNESCAPED_UNICODE)]);
        if ($chatDetailId > $aiChatRecordData['last_chat_detail_id'])
        {
            $aiChatRecordModel->UpdateData($healChatId, $this->user['id'], [
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $this->request->time(),
            ]);
        }
    }

    public function changeStoryLine()
    {
        $healChatId = input('heal_chat_id/d', 0);
        $content = trim(input('content/s', ''));
        $type = input('type/d', 0);
        if (empty($healChatId) || !in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $aiChatRecordModel = new AiChatRecord();
        $aiChatRecordData = $aiChatRecordModel->getInfoById($healChatId);
        if (!$aiChatRecordData || $aiChatRecordData['uid'] != $this->user['id'])
        {
            return show(config('code.error'), '服务异常，伙伴不存在～');
        }
        if ($aiChatRecordData['type'] !== 1)
        {
            return show(config('code.error'), '服务异常，不支持此操作～');
        }
        $aiChatStoryLineModel = new AiChatStoryLine();
        $aiChatUserConfigModel = new AiChatUserConfig();
        if ($type === 2)
        {
            if (empty($content))
            {
                return show(config('code.error'), '请输入剧情内容～');
            }
            if (mb_strlen($content) > 120)
            {
                return show(config('code.error'), '剧情内容不能超过120字～');
            }
            $aliRes = AliyunFilterWordV2::checkAIText($content);
            if ($aliRes['status'] === false)
            {
                return show(0, '检测到敏感内容');
            }
            $slData = [
                'uid' => $this->user['id'],
                'chat_id' => $healChatId,
                'config_id' => $aiChatRecordData['config_id'],
                'content' => $content,
                'first_msg' => '',
                'create_time' => $this->request->time(),
            ];
            $resSlId = $aiChatStoryLineModel->SaveData($slData);
            $firstStr = '剧情已就绪，快试着和我聊聊吧。';
            $isIgnore = 1;
        } else
        {
            $changeNum = $aiChatStoryLineModel->getChangeStoryLineNum($this->user['id']);
            if ($changeNum > 20)
            {
                return show(config('code.error'), '今天更换过20次剧情了，请明天再试～');
            }
            $roomConfigData = $aiChatUserConfigModel->getInfoById($aiChatRecordData['config_id']);
            $cfg = $roomConfigData['config']['config'];
            $resSlId = $aiChatUserConfigModel->randStoryLineIds($cfg, $roomConfigData['sl_id']);
            $storyLineData = $aiChatStoryLineModel->getInfoById($resSlId);
            $content = $storyLineData['content'];
            $firstStr = $storyLineData['first_msg'];
            $isIgnore = 0;
        }

        $res = $aiChatUserConfigModel->UpdateData($aiChatRecordData['config_id'], ['sl_id' => $resSlId]);
        if ($res)
        {
            // 添加 剧情首语句
            $insertData = [
                [
                    'chat_id' => $healChatId,
                    'uid' => $this->user['id'],
                    'type' => 1,    //  1=>APP消息 2=>用户发送消息
                    'title' => '',
                    'content' => $firstStr, // 提问问题
                    'data_type' => 1,
                    'extend' => ['is_first' => 1, 'is_ignore' => $isIgnore, 'sl_id' => $resSlId],  // stream = 1 获取流式数据 2 结果已获取
                    'result_data' => '',
                    'option_id' => '',
                    'pid' => 0,
                    'create_time' => $this->request->time(),
                ],
            ];
            $aiChatRecordDetailsModel = new AiChatRecordDetails();
            $resData = $aiChatRecordDetailsModel->SaveData($healChatId, $insertData);
            $chatDetailId = $resData[0]['id'];

            $aiChatRecordModel->UpdateData($healChatId, $this->user['id'], [
                'last_chat_detail_id' => $chatDetailId,
                'last_chat_detail_time' => $this->request->time(),
            ]);

            if ($type === 1)
            {   // 增加 剧情编辑次数
                $aiChatStoryLineModel->storyLineChangeNumInc($this->user['id']);
            }

            return show(config('code.success'), '请求成功', [
                'content' => $content, 'data' => [
                    'id' => $chatDetailId,
                    'content' => $firstStr,
                    'type' => 1,
                    'is_stream_reload' => 0,
                ],
            ]);
        } else
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }

    /**
     * 举报信息
     * @return \think\response\Json
     * @throws \Exception
     */
    public function reportInfo()
    {
        $data = (new Informant())->getInformantListFromCache(3);
        $array = [];
        foreach ($data as $datum)
        {
            $id = (int)$datum['id'];
            $content = $datum['content'];
            $array[] = [
                'id' => $id,
                'name' => $content,
            ];
        }
        return show(config('code.success'), '请求成功', $array);
    }

    /**
     * 举报
     * @return Json
     * @throws \Exception
     */
    public function report()
    {
        $healChatId = input('heal_chat_id/d', 0);
        $cId = input('c_id/d', 0);
        //获取举报信息
        $informantInfo = (new Informant())->getInfoById($cId, ['type']);
        if (!$informantInfo || (int)$informantInfo['type'] !== 3)
        {
            return show(config('code.error'), '举报异常，请稍后再试');
        }
        $roomInfo = (new AiChatRecord())->getInfoById($healChatId, ['uid']);
        if (!$roomInfo || $this->user['id'] != $roomInfo['uid'])
        {
            return show(config('code.error'), '举报异常，请稍后再试');
        }
        //申诉添加举报表
        $data = [
            'type' => 6,
            'comment_id' => $healChatId,
            'info_id' => $cId,
            'uid' => $this->user['id'],
            'create_time' => time(),
        ];
        $res = (new MiddleInformant())->SaveData($data);
        if ($res)
        {
            return show(config('code.success'), '请求成功');
        }
        return show(config('code.error'), '服务异常，请稍后再试～');
    }

    public function chatStop()
    {
        $aiChatUserDurationModel = new AiChatUserDuration();
        $resDuration = $aiChatUserDurationModel->userDurationEnd($this->user['id']);

        return show(config('code.success'), '请求成功', ['duration' => $resDuration]);
    }

    /**
     * 获取时长任务信息
     * @return \think\response\Json
     * @throws \Exception
     */
    public function getDurationTaskInfo()
    {
        $taskConfig = config('ai_chat_room.task_data');
        $chatDuration = (new AiChatUserDuration())->getUserDuration($this->user['id'], true);
        $sucTasks = (new AiChatUserDurationChangeRecord())->getTaskSuccessData($this->user['id']);
        $list = [];
        foreach ($taskConfig['list'] as $item)
        {
            if (in_array($item['id'], $sucTasks, true))
            {   // 已完成
                $btnName = $item['btn_name2'];
                $type = 0;
                $target = 'local';
                $link = 'empty';
            } else
            {   // 未完成
                $btnName = $item['btn_name1'];
                $type = 1;
                $target = $item['target'];
                $link = $item['link'];
            }
            $btnInfo = [
                'type' => $type,
                'btn_name' => $btnName,
                'target' => $target,
                'link' => $link,
            ];
            $list[] = [
                'name' => $item['name'],
                'duration_time' => sprintf("%d分钟", (int)$item['duration'] / 60),
                'desc' => $item['desc'],
                'btn_info' => $btnInfo,
            ];
        }
        $resData = [
            'duration' => $chatDuration['res_duration'],
            'list' => $list,
            'rule_desc' => $taskConfig['rule'],
            'pay' => 0,
        ];
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 任务完成
     * @return \think\response\Json
     * @throws \Exception
     */
    public function durationTaskSuccess()
    {
        $taskId = input('type/d', 0);
        if (!in_array($taskId, [3], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'AiChatRoomUser.durationTaskSuccess', 'type' => $taskId], 3))
        {// mark 17333657763 手机号的uid为10834769，可以测试并发
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $aiChatUserDurationChangeRecordModel = new AiChatUserDurationChangeRecord();
        $res = $aiChatUserDurationChangeRecordModel->durationTaskSuccess($this->user['id'], $taskId);

        switch ($res['status'])
        {
            case 1: // 任务已经完成过了
                return show(config('code.success'), '请求成功', ['duration' => $res['duration']]);
            case 2: // 任务完成
                return show(config('code.success'), '请求成功', ['duration' => $res['duration']]);
            default:
                return show(config('code.error'), '服务异常，请稍后再试～');
        }
    }
}
